<template>
	<div>
		<el-row :gutter="30" style="width: 95%;margin: 0 auto">
			<el-col :span="24" v-for="(tData, tIndex) in settings" :key="tData.id" class="margin-bottom">
				<el-card shadow="never">
					<div slot="header" class="card-header flex justify-between align-center flex-no-wrap">
						<div class="flex-none flex justify-start align-center">
							<div class="margin-right text-bold">时间段</div>
							<el-date-picker :clearable="false" size="mini" v-model="tData.dateRange" type="daterange"
								range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy年MM月dd日"
								value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']"
								style="width:350px; margin: 0;"
								@blur="(val) => changeSetDateRange(val, tIndex)">
							</el-date-picker>
							<!-- <el-button type="text" size="mini" style="margin: 0 0 0 5px;"
								v-show="!tData.canEditDateRange" @click="changeTDataCanEdit(tIndex, true)">修改
							</el-button>
							<el-button type="text" size="mini" style="margin: 0 0 0 5px;"
								v-show="!!tData.canEditDateRange" @click="changeTDataCanEdit(tIndex, false)">保存
							</el-button> -->
						</div>
						<div class="flex-none flex justify-end align-center">
							<el-tooltip slot="header" placement="top" content="默认排斥该配置已选点位">
								<el-button icon="el-icon-circle-plus-outline" type="primary" plain size="mini" @click="addPoint(tIndex)">
									增加点位</el-button>
							</el-tooltip>
							<el-tooltip slot="header" placement="top" content="默认排斥该配置已选楼盘">
								<el-button icon="el-icon-circle-plus-outline" type="primary" plain size="mini" @click="addBuilding(tIndex)">
									增加楼盘</el-button>
							</el-tooltip>
							<el-tooltip slot="header" placement="top" content="复用相同楼盘,重新选择时间段" style="margin:0 10px">
								<PointPlanSettingPrevChooseDateRange buttonText="复用楼盘" buttonSize="mini" buttonPlain buttonIcon="el-icon-document-copy" @add-setting="(val) => copyBuilding(val, tIndex)" />
							</el-tooltip>
							<el-button icon="el-icon-delete" type="danger" plain size="mini" @click="delSet(tIndex)">
								删除配置</el-button>
						</div>
					</div>
					<el-divider><span class="text-bold">选中的点位</span></el-divider>
					<el-table :data="(tData.buildings || [])" row-key="id" size="mini" show-summary
						:summary-method="(obj) => dataSummary(obj, tIndex)" header-row-class-name="choosed-data" row-class-name="choosed-data"
						class="choosed-data-table">
						<el-table-column min-width="130" prop="name" label="楼盘"></el-table-column>
						<el-table-column min-width="100" align="center" :prop="''+pt.id" v-for="pt in tData.pointTypes"
							:key="pt.id">
							<el-tooltip slot="header" placement="top" content="可点击数字,调整点位">
								<span>{{pt.name}}<i class="el-icon-question"></i></span>
							</el-tooltip>
							<template slot-scope="scope">
								<el-button class="text-underline" type="text" size="mini" @click="editCount(tIndex, scope.row.id, pt.id)">
									{{(tData.to[scope.row.id+'_'+pt.id] || []).length}}
								</el-button>
							</template>
						</el-table-column>
						<el-table-column label="操作" width="80px" align="center" fixed="right">
							<template slot-scope="scope">
								<el-button icon="el-icon-delete" size="mini" plain type="danger" @click="delBuilding(tIndex, scope.$index, scope.row.id)" circle></el-button>
							</template>
						</el-table-column>
					</el-table>
					<el-divider v-if="(tData.out.buildings || []).length > 0"><span
							class="text-red text-bold">不满足的点位</span></el-divider>
					<el-table v-if="(tData.out.buildings || []).length > 0"
						:data="(tData.out.buildings || [])" row-key="id" size="mini" show-summary
						:summary-method="(obj) => dataOutSummary(obj, tIndex)" header-row-class-name="out-data" row-class-name="out-data"
						class="out-data-table">
						<el-table-column min-width="130" prop="name" label="楼盘"></el-table-column>
						<el-table-column min-width="100" :label="pt.name" align="center" :prop="''+pt.id" v-for="pt in tData.pointTypes"
							:key="pt.id">
							<template slot-scope="scope">
								{{(tData.out.to[scope.row.id+'_'+pt.id] || []).length}}
							</template>
						</el-table-column>
					</el-table>
				</el-card>
			</el-col>
		</el-row>
		
		<PointPlanSettingEditSetting ref="PointPlanSettingEditSetting" @confirm-setting="completeSetting"></PointPlanSettingEditSetting>
		
		<!-- 具体点位可视化弹框 -->
		<exact-view ref="exactView" :exactVisible.sync="exactVisible" :toExact="exactToExact" :viewData="exactToExactViewData"
			:can="exactCan" :total="exactTotal" :key="exactTimer" @choosed="choosedToExact" :leafShowType="2"/>
	</div>
</template>

<script>
	import common from '@/utils/common.js';
	import {
		cloneDeep
	} from 'lodash'
	import {
		formatDate
	} from '@/utils/util.js'
	import {
		first_search
	} from '@/api/business/building/point_plan.js';
	import pointPlanUtil from './js/pointPlanUtil.js';
	import ExactView from '@/components/TencentMap/ExactView';
	import PointPlanSettingEditSetting from '@/components/PointPlanSetting/editSetting'
	import PointPlanSettingPrevChooseDateRange from '@/components/PointPlanSetting/prevChooseDateRange'
	export default {
		name: 'PointPlanSettingShowSetting',
		// beforeRouteLeave(to, from, next) {
		// 	this.$destroy();
		// 	next();
		// },
		components: {
			ExactView,
			PointPlanSettingEditSetting,
			PointPlanSettingPrevChooseDateRange
		},
		props: {
			settings: {
				type: Array,
				default: () => []
			},
			useEditSetting:{
				type: Boolean,
				default: true
			}
		},
		data(){
			return {
				addBParamsIndex: null,
				isAddB: false,
				
				exactParams: {},
				exactVisible: false,
				exactToExact: [],
				exactToExactViewData: [],
				exactTotal: 0,
				exactCan: 0,
				exactTimer: '',
			}
		},
		watch: {
			// settings: { //深度监听，可监听到对象、数组的变化
			// 	handler(val, oldVal) {
			// 		// this.$emit('update:settings', val);
			// 		this.calSetSum();
			// 	},
			// 	deep: true //true 深度监听
			// }
			settings(val) {
				this.$emit('update:settings', val);
				this.calSetSum();
			}
		},
		methods: {
			// 改变配置块时间段可编辑
			changeTDataCanEdit(tIndex, can = false) {
				const that = this;
				if(!!can) {
					that.settings[tIndex].to_origin = JSON.parse(JSON.stringify(that.settings[tIndex].to));
					that.settings[tIndex].out = {};
				}
				that.settings[tIndex].canEditDateRange = can;
				that.$forceUpdate();
			},
			// 改变时间段
			changeSetDateRange(val, tIndex) {
				const that = this;
				let params = {};
				const loading = common.showLoading('检验中');
				params.date_range = {
					start_at: that.settings[tIndex].dateRange[0],
					end_at: that.settings[tIndex].dateRange[1]
				};
				params.building_ids = that.settings[tIndex].buildings.map(b => (b.id));
				params.point_type_ids = that.settings[tIndex].pointTypes.map(p => (p.id));
				if(!!that.settings[tIndex].auto_id) params.point_plan_setting_ids_in = [that.settings[tIndex].auto_id];
				first_search(params)
					.then(({
						data: {
							buildings,
							point_type_ids
						}
					}) => {
						let tempMap = new Map();
						let outTo = {};
						let canTo = {};
						(buildings || []).forEach(build => {
							const pointKeys = Object.keys(build.points || {});
							(pointKeys || []).forEach(pkey => {
								(build.points[pkey].can_devices || []).forEach(device => {
									const key = build.id + '_' + pkey;
									let deviceSet = tempMap.get(key) || new Set();
									deviceSet.add(parseInt(device.id));
									tempMap.set(key, deviceSet);
								});
							});
						});
						
						const toKeys = Object.keys(that.settings[tIndex].to);
						(toKeys || []).forEach(key => {
							const canSet = tempMap.get(key) || new Set();
							const devices = that.settings[tIndex].to[key] || [];
							let canDevices = [];
							let outDevices = [];
							devices.forEach(d => {
								if(!!canSet.has(parseInt(d.id))){
									canDevices.push(d);
								}else{
									outDevices.push(d);
								}
							});
							canTo[key] = canDevices;
							if((outDevices || []).length > 0) outTo[key] = outDevices;
						});
						
						that.$set(that.settings[tIndex], 'to', canTo);
						
						const outToKeys = Object.keys(outTo) || [];
						if(outToKeys.length > 0){
							let buildSet = new Set();
							outToKeys.forEach(key => {
								const b_p = key.split('_');
								buildSet.add(parseInt(b_p[0]));
							});
							const outBuildings = (that.settings[tIndex].buildings || []).filter(b => {
								return buildSet.has(parseInt(b.id));
							});
							that.$set(that.settings[tIndex], 'out', {
								to: outTo,
								buildings: outBuildings
							});
						}
						
						that.calSetSum();
						
						loading.close();
					});
			},
			
			// 点击数量
			async editCount(tIndex, buildingId, pointId){
				const that = this;
				const check = await that.checkSaneDateRange(tIndex);
				if(!check) return false;
				
				let params = {};
				const loading = common.showLoading('加载中');
				params.date_range = {
					start_at: that.settings[tIndex].dateRange[0],
					end_at: that.settings[tIndex].dateRange[1]
				};
				params.building_ids = [buildingId];
				params.point_type_ids = [pointId];
				params.device_ids_in = (that.settings[tIndex].to[buildingId+'_'+pointId] || []).map(d => {
					return d.id;
				});
				that.exactParams = params;
				that.exactParams.tIndex = tIndex;
				first_search(params)
					.then(({
						data: {
							buildings,
							point_type_ids
						}
					}) => {
						const origin_data = pointPlanUtil.getOriginData(buildings, params.point_type_ids, []);
						const filter_data = pointPlanUtil.filterDistTableData(origin_data, new Map());
						// that.settings[tIndex].ruleMap
						const points = (((filter_data || [])[0] || {}).points || {})[''+pointId];
						if(!!points && points.can_devices.length > 0){
							const {
								list,
								count
							} = pointPlanUtil.getExactViewData(points, pointId, new Map());
							// (that.settings[tIndex].ruleMap || new Map()).get(''+pointId) 
							that.exactToExact = that.settings[tIndex].to[buildingId+'_'+pointId] || [];
							that.exactToExactViewData = list;
							that.exactTotal = count;
							that.exactCan = points.can_count || 0;
							that.exactVisible = true;
						}else{
							common.messageWarning('无可选点位！');
						}
						loading.close();
					});
			},
			// 调整数量
			choosedToExact(val){
				const that = this;
				that.$set(that.settings[that.exactParams.tIndex].to, that.exactParams.building_ids[0]+'_'+that.exactParams.point_type_ids[0], val || []);
				//that.$set(that.settings, that.exactParams.tIndex, Object.assign({}, that.settings[that.exactParams.tIndex]));
				that.calSetSum();
			},
			// 删除楼盘
			async delBuilding(tIndex, index, buildingId){
				const that = this;
				const check = await that.checkSaneDateRange(tIndex);
				if(!check) return false;
				
				const confirm = await common.confirmDialog('您确定要删除该楼盘？');
				if (!!confirm) {
					that.$set(that.settings[tIndex], 'out', {});
					
					that.settings[tIndex].buildings.splice(index, 1);
					const keys = Object.keys(that.settings[tIndex].to);
					let removeKeys = [];
					(keys || []).forEach(key => {
						const str = key.split('_');
						if(''+str[0] === ''+buildingId){
							removeKeys.push(key);
						}
					});
					(removeKeys || []).forEach(key => {
						delete that.settings[tIndex].to[''+key];
					});
					if((that.settings[tIndex].buildings || []).length == 0) that.settings.splice(tIndex, 1);
					that.calSetSum();
				}
			},
			// 复用楼盘
			async copyBuilding({dateRange},tIndex){
				const that = this;
				const params = {
					dateRange: dateRange,
					building_area_ids: that.settings[tIndex].buildings.map(b => (b.id))
				};
				if(!!that.useEditSetting){
					that.isAddB = false;
					that.$refs.PointPlanSettingEditSetting.showAdd(params);
				}else{
					that.$emit('add-set', params);
				}
			},
			// 删除配置
			async delSet(tIndex){
				const that = this;
				const confirm = await common.confirmDialog('您确定要删除该配置？');
				if (!!confirm) {
					that.settings.splice(tIndex, 1);
				}
			},
			// 配置增加点位
			async addPoint(tIndex){
				const that = this;
				const check = await that.checkSaneDateRange(tIndex);
				if(!check) return false;
				that.$set(that.settings[tIndex], 'out', {});
				
				let outPointIds = [];
				const keys = Object.keys(that.settings[tIndex].to) || [];
				keys.forEach(key => {
					outPointIds = [...outPointIds, ...(that.settings[tIndex].to[key] || []).map(p => p.id)];
				});
				const params = {
					dateRange: that.settings[tIndex].dateRange,
					outPointIds: outPointIds,
					point_type_ids: that.settings[tIndex].pointTypes.map(p => (p.id))
				};
				
				if(!!that.useEditSetting){
					that.addBParamsIndex = tIndex;
					that.isAddB = true;
					that.$refs.PointPlanSettingEditSetting.showAdd(params);
				}else{
					that.$emit('add-point', Object.assign({setIndex: tIndex}, params));
				}
				
			},
			// 配置增加楼盘
			async addBuilding(tIndex){
				const that = this;
				const check = await that.checkSaneDateRange(tIndex);
				if(!check) return false;
				that.$set(that.settings[tIndex], 'out', {});
				
				const params = {
					dateRange: that.settings[tIndex].dateRange,
					outBuildingIds: that.settings[tIndex].buildings.map(b => (b.id)),
					point_type_ids: that.settings[tIndex].pointTypes.map(p => (p.id))
				};
				
				if(!!that.useEditSetting){
					that.addBParamsIndex = tIndex;
					that.isAddB = true;
					that.$refs.PointPlanSettingEditSetting.showAdd(params);
				}else{
					that.$emit('add-build', Object.assign({setIndex: tIndex}, params));
				}
				
			},
			// 增加的楼盘
			completeSetting(set){
				const that = this;
				if(!!that.useEditSetting){
					if(!!that.isAddB){
						const {pointTypes, buildings, to} = set;
						// 点位类型的变化
						let tempP = [];
						let curPointTypes = that.settings[that.addBParamsIndex].pointTypes || [];
						let curPointTypesMap = new Map();
						curPointTypes.forEach(p => {
							curPointTypesMap.set(parseInt(p.id), p);
						});
						(pointTypes || []).forEach(p => {
							if(!curPointTypesMap.get(parseInt(p.id))) tempP.push(p);
						});
						that.$set(that.settings[that.addBParamsIndex], 'pointTypes', [...that.settings[that.addBParamsIndex].pointTypes, ...tempP].sort((a, b) => {
							return a.id - b.id;
						}));
						
						// 楼盘
						that.$set(that.settings[that.addBParamsIndex], 'buildings', [...that.settings[that.addBParamsIndex].buildings, ...buildings]);
						
						// 分配数量
						that.$set(that.settings[that.addBParamsIndex], 'to', Object.assign({}, that.settings[that.addBParamsIndex].to, to));
					}else{
						that.settings.push(Object.assign({}, set, {
							canEditDateRange: true
						}))
					}
					that.calSetSum();
				}
			},
			// 计算合计值
			calSetSum() {
				const that = this;
				(that.settings || []).forEach(set => {
					let sum = {};
					const keys = Object.keys(set.to || {}) || [];
					keys.forEach(key => {
						const kSP = key.split('_');
						let sumP = sum['' + kSP[1]] || 0;
						sumP += (set.to[key] || []).length;
						sum['' + kSP[1]] = sumP;
					});
					set.sum = sum;
					
					let sum_out = {};
					const keys_out = Object.keys(set.out.to || {}) || [];
					keys_out.forEach(key => {
						const kSP = key.split('_');
						let sumP = sum_out['' + kSP[1]] || 0;
						sumP += (set.out.to[key] || []).length;
						sum_out['' + kSP[1]] = sumP;
					});
					set.sum_out = sum_out;
				});
			},
			// 检查时间段是否处于编辑态
			checkSaneDateRange(tIndex){
				const that = this;
				return new Promise((resolve, reject) => {
					// if(!!that.settings[tIndex].canEditDateRange){
					// 	common.messageWarning('请先保存时间段！');
					// 	resolve(false);
					// }else{
					// 	resolve(true)
					// }
					resolve(true)
				})
			},
			// 合计行
			dataSummary({
				columns,
				data
			}, tIndex) {
				const that = this;
				const sums = [];
				const maxC = (columns || []).length;
				(columns || []).forEach((column, index) => {
					if (index === 0) {
						sums[index] = '合计';
						return;
					}
					if (index > 0 && index < maxC - 1 ){
						sums[index] = that.settings[tIndex].sum[column.property] || 0;
					}
				});
				return sums;
			},
			// 踢出合计行
			dataOutSummary({
				columns,
				data
			}, tIndex) {
				const that = this;
				const sums = [];
				const maxC = (columns || []).length;
				(columns || []).forEach((column, index) => {
					if (index === 0) {
						sums[index] = '合计';
						return;
					}
					if (index > 0 ){
						sums[index] = that.settings[tIndex].sum_out[column.property] || 0;
					}
				});
				return sums;
			},
		}
	}
</script>

<style>
</style>
